#! /usr/bin/perl -w

use strict;
use Term::ANSIColor qw(:constants);

$Term::ANSIColor::AUTORESET = 1;
    
my @fmts;
my @dirs;
my $vtab = '|';

sub search($) {
    my $cwd = shift;
    push @dirs, $cwd;
    my $dir = join '/', @dirs;
    
    my @entries = listdir( $dir );
    my $total = scalar @entries;

    foreach my $file (@entries) {
        $vtab = ( $total == 1 ? '\\' : '|' );
        display( $file );
        if ( -d $dir . "/" . $file ) {
            push @fmts, $total == 1 ? "    " : "|    ";
            &search( $file )
        }
        $total --;
    }

    pop @dirs;
    pop @fmts;
}

sub listdir($) {

    my $dir = shift;
    my @entries;

    opendir( DIR, $dir ) or die qq{Can not opendir "$dir"};
    while ($_ = readdir(DIR)) {
        next if $_ eq '.';
        next if $_ eq '..';

        push @entries, $_;
    }
    closedir DIR;

    return @entries;
}


sub display($) {
    my $e = shift;

    print join ("", @fmts). $vtab . "--" . get_COLOR($e) . $e . get_RESET() . "\n";
}

sub get_COLOR($) {

    return '' unless -t STDOUT;

    my $e = shift;
    my $abs = join("/", @dirs) . "/" . $e;
    my $color;

    if ( -d $abs ) {
        $color = BLUE;
    }
    elsif ( -S _ ) {
        $color = MAGENTA;
    }
    elsif ( -x _ ) {
        $color = GREEN;
    }
    elsif ( -l $abs ) {
        $color = CYAN;
    }
    else {
        $color = '';
    }

    return BOLD . "$color";
}

sub get_RESET {
    return '' unless -t STDOUT;
    RESET;
}

##########################

my $start = shift || '.';
search( $start );
